<template>
  <el-form ref="form" :model="form" :rules="rules">
    <el-form-item prop="content">
      <el-input
        type="textarea"
        :placeholder="typeof(parentId)=='undefined'?'添加评论':'添加回复'"
        v-model="form.content"
        maxlength="50"
        show-word-limit
        autosize
      ></el-input>
    </el-form-item>
    <el-button type="primary" size="mini" @click="createComment"
      >提交</el-button
    >
    <el-button @click="resetForm" size="mini">清空</el-button>
  </el-form>
</template>

<script>
export default {
  props: {
    articleId: { type: Number },
    parentId: { type: Number },
  },
  data() {
    var checkComment = (rule, value, callback) => {
      if (value.replace(/\n+/g, "")=="") {
        return callback(new Error("不能为空"));
      }else{
        callback()
      }
    };
    return {
      form: {
        content: "",
      },
      rules: {
        content: [{ required: true, message: "不能为空", trigger: blur },{ validator: checkComment, trigger: "blur" },],
      },
    };
  },
  methods: {
    createComment() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.createCommentReq();
        } else {
          return false;
        }
      });
    },
    createCommentReq() {
      // article_id, content, parent_id
      let content = this.form.content.replace(/\n+/g, "\n")
      let data = {
          content: content,
          article :this.articleId
      }
      if(typeof(this.parentId)!="undefined"){
          data.parent = this.parentId
      }
      this.$http.post('comments/', data).then(res=>{
        this.$store.commit('setCommentListKey', res.data.id)
        this.form.content = ""
      })
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
  },
};
</script>

<style>
</style>
